package com.lituoxy.dialer;

/**
 * 作者：许航晨 on 2017/4/18 16:22
 * 邮箱：948340983@qq.com
 */

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.huawei.rcs.call.CallApi;
import com.huawei.rcs.call.CallSession;

import org.json.JSONException;
import org.json.JSONObject;

//呼叫界面
public class ACT_DemoCallOutGoing extends Activity {

    private String calleeNumber, name;
    private boolean isVideoCall;

    CallSession callSession = null;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                JSONObject object = new JSONObject(msg.obj.toString());
                if (object != null) {
                    //打开接听界面
                    /*Intent intentTalking = new Intent();
                    intentTalking.setClass(ACT_DemoCallOutGoing.this, ACT_DemoCallTalking.class);
                    startActivity(intentTalking);
                    Intent newIntent = new Intent(ACT_DemoCallOutGoing.this, ACT_DemoCallIncoming.class);
                    newIntent.putExtra("session_id", object.getString("sessionId"));
                    newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    ACT_DemoCallOutGoing.this.startActivity(newIntent);*/
                    //CallApi.getCallSessionById()
                    // callSession = CallApi.getCallSessionById(object.getLong("sessionId"));
                    object.getString("sessionId");
                    ACT_DemoCallOutGoing.this.finish();
                    //提示进行拨号
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    };
    private String huawei_callee_number;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.demo_call_outgoing);
        /* Get call information from an Intent. */
        getExtras();
        initViews();
       /* HttpRequestDispatch dispatch = new HttpRequestDispatch(this, handler, calleeNumber);
        new Thread(dispatch).start();*/
        /*Init a call*/
        initCall();

        /*register a broadcast receiver, it will be called once calling status is changed .注册广播接收器，一旦呼叫状态改变，它将被调用。*/
        LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(callStatusChangedReceive,
                new IntentFilter(CallApi.EVENT_CALL_STATUS_CHANGED));
    }

    private void getExtras() {
        calleeNumber = getIntent().getStringExtra("callee_number");
        huawei_callee_number = getIntent().getStringExtra("huawei_callee_number");
        name = getIntent().getStringExtra("name");
        isVideoCall = getIntent().getBooleanExtra("is_video_call", false);
    }

    private void initViews() {
        TextView txtContactNumber = (TextView) findViewById(R.id.call_txt_contact_num_outgoing);
        TextView txtCallType = (TextView) findViewById(R.id.call_txt_call_state_outgoing);
        txtContactNumber.setText(name != null ? name : "拨打 电话: " + calleeNumber);
        //txtCallType.setText(isVideoCall ? "视频电话" : "音频电话");

    }

    private void initCall() {
        callSession = CallApi.initiateAudioCall(huawei_callee_number);//拨打华为网络电话
        /* You had to finish the program when you received an error code. */
        if (callSession.getErrCode() != CallSession.ERRCODE_OK) {//拨打网络电话失败
            Toast.makeText(getApplicationContext(), "initiate call failed", Toast.LENGTH_LONG).show();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, 3000);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        /* Unregister broadcast receiver which you register before. */
        LocalBroadcastManager.getInstance(getApplicationContext())
                .unregisterReceiver(callStatusChangedReceive);
    }

    /* Deal with cancel event. */
    public void onClick_Cancel(View v) {
        if (callSession.getErrCode() != CallSession.ERRCODE_OK) {
            finish();
            return;
        }

        callSession.terminate();
    }

    /* If calling status has become connected, it will goto call talking layout.
     * Otherwise, the calling request maybe rejected by callee. */
    private BroadcastReceiver callStatusChangedReceive = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            CallSession session = (CallSession) intent.getSerializableExtra(CallApi.PARAM_CALL_SESSION);
            if (callSession == null) {
                return;
            }
            if (!callSession.equals(session)) {
                return;
            }
            int newStatus = intent.getIntExtra(CallApi.PARAM_NEW_STATUS, CallSession.STATUS_IDLE);
            switch (newStatus) {
                case CallSession.STATUS_CONNECTED:
                    Intent intentTalking = new Intent();
                    if (session.getType() == CallSession.TYPE_AUDIO) {
                        intentTalking.setClass(ACT_DemoCallOutGoing.this, ACT_DemoCallTalking.class);
                    } else {
                        //intentTalking.setClass(ACT_DemoCallOutGoing.this , ACT_DemoCallTalkingVideo.class);
                    }
                    startActivity(intentTalking);
                    finish();
                    break;
                case CallSession.STATUS_IDLE:
                    finish();
                    break;
                default:
                    break;
            }
        }
    };
}
